import { ref } from 'vue';
import { ElMessageBox } from 'element-plus';
import { useKnowledgeStore } from '@/store/kg/knowledge';

// 知识点store
const knowledgeStore = useKnowledgeStore();

// 用于删除的知识点ID数组
export const deleteIds = ref<string[]>([]);
// 知识点对话框的显示状态
export const knowledgeDialogVisible = ref(false);
// 分配前置知识点对话框的显示状态
export const assignPrerequisitesDialogVisible = ref(false);
// 当前操作的知识点ID
export const currentKnowledgeId = ref<string>('');
// 当前正在编辑的知识点对象
export const currentKnowledge = ref<any>({});
// 表单加载状态
export const formLoading = ref(false);
// 操作类型（新增/编辑）
export const operationType = ref<'add' | 'update'>('add');

/**
 * 搜索知识点
 */
export const onSearch = async () => {
  await knowledgeStore.getKnowledgeList();
};

/**
 * 添加知识点
 */
export const onAdd = () => {
  operationType.value = 'add';
  currentKnowledge.value = {
    level: 1, // 默认为基础
  };
  knowledgeDialogVisible.value = true;
};

/**
 * 编辑知识点
 */
export const onUpdate = (row: any) => {
  operationType.value = 'update';
  currentKnowledge.value = { ...row };
  currentKnowledgeId.value = String(row.nodeId);
  knowledgeDialogVisible.value = true;
};

/**
 * 删除知识点
 */
export const onDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除知识点 ${row.name} 吗？`, '删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await knowledgeStore.deleteKnowledge(String(row.nodeId));
    onSearch();
  });
};

/**
 * 批量删除知识点
 */
export const onDeleteBatch = () => {
  ElMessageBox.confirm(`确认删除选中的 ${deleteIds.value.length} 条数据吗？`, '批量删除确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const promises = deleteIds.value.map(id => knowledgeStore.deleteKnowledge(id));
    await Promise.all(promises);
    onSearch();
  });
};

/**
 * 分配前置知识点
 */
export const onAssignPrerequisitesToKnowledge = (row: any) => {
  currentKnowledgeId.value = String(row.nodeId);
  assignPrerequisitesDialogVisible.value = true;
};

/**
 * 保存知识点表单
 */
export const onSaveKnowledge = async (formRef: any) => {
  if (!formRef) return false;

  return await formRef.validate(async (valid: boolean) => {
    if (!valid) return false;

    formLoading.value = true;
    try {
      if (operationType.value === 'add') {
        if (!currentKnowledge.value.courseId && knowledgeStore.selectedCourseId) {
          currentKnowledge.value.courseId = knowledgeStore.selectedCourseId;
        }
        const result = await knowledgeStore.createKnowledge(
          String(currentKnowledge.value.courseId),
          currentKnowledge.value
        );
        return !!result;
      } else {
        const result = await knowledgeStore.updateKnowledge(currentKnowledgeId.value, currentKnowledge.value);
        return !!result;
      }
    } finally {
      formLoading.value = false;
    }
  });
};
